<template>
  <div class="drag-file-area-container">
    <div
      class="drag-file-area"
      @dragenter="handleDragEnter"
      @dragover="handleDragOver"
      @drop="handleDrop"
    >
      <div class="drag-file-area-header">
        <div class="icon-upload"></div>
        <div class="text-upload">将目录或多个文件拖拽到此处进行扫描</div>
      </div>
      <div class="drag-file-area-content">支持的文件类型：.jpg、.jpeg、.png、.bmp、.gif、.webp</div>
      <div class="drag-file-area-footer">每个文件允许的最大尺寸：1MB</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {} from 'vue'

const emit = defineEmits(['addFile'])

const handleDragEnter = (event) => {
  event.preventDefault()
  event.stopPropagation()
}

const handleDragOver = (event) => {
  event.preventDefault()
  event.stopPropagation()
}

const handleDrop = (event) => {
  event.preventDefault()
  event.stopPropagation()
  const dataTransferList = event.dataTransfer.items
  for (let i = 0; i < dataTransferList.length; i++) {
    const dataTransferItem = dataTransferList[i]
    const fileEntry = dataTransferItem.webkitGetAsEntry()

    addFile(fileEntry)
  }
}

const addFile = (fileEntry) => {
  if (fileEntry.isFile) {
    fileEntry.file((file) => {
      emit('addFile', file)
    })
  } else if (fileEntry.isDirectory) {
    const reader = fileEntry.createReader()
    reader.readEntries((entries) => {
      entries.forEach((entry) => {
        addFile(entry)
      })
    })
  }
}
</script>

<style lang="scss" scoped>
.drag-file-area-container {
  padding: 20px;
  .drag-file-area {
    height: 200px;
    padding: 20px;
    border: 1px dashed #ccc;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
